package com.hp.controller;

import com.github.pagehelper.PageInfo;
import com.hp.bean.Customer;
import com.hp.service.CustomerService;
import com.hp.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService service;
    @RequestMapping("/selectfind")
    @ResponseBody
    public Object find(
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "limit",defaultValue = "5")Integer limit,
            HttpSession session
    ){
        PageInfo<Customer> pageInfo=service.selectfind(page,limit);
        session.setAttribute("pageInfo",pageInfo);
        return JsonData.buildSuccess(pageInfo);
    }

    @RequestMapping("/getList")
    @ResponseBody
    public Object getList(Integer id){
       List<Customer> list= service.getList(id);
       List<Map<String,String>> listMap=new ArrayList<>();
        for (Customer customer: list) {
            HashMap<String, String> map = new HashMap<>();
            map.put("value",customer.getId().toString());
            map.put("title",customer.getName());
            listMap.add(map);
        }
        return listMap;
    }

    /**
     * 添加
     */
    @RequestMapping("/add")
    @ResponseBody
    public Object add(Customer obj) {
        int i = service.add(obj);
        return JsonData.buildSuccess(i>0?"添加成功！":"添加失败！");
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public Object update(Customer obj) {
        int i = service.upp(obj);
        return JsonData.buildSuccess(i>0?"修改成功！":"修改失败！");
    }
    /**
     * 删除
     */
    @RequestMapping("/del")
    @ResponseBody
    public Object del(Customer obj) {
        obj.setDel("1");
        ////逻辑删除,走的修改方法
        int i = service.upp(obj);
        return JsonData.buildSuccess(i>0?"删除成功！":"删除失败！");
    }

    @RequestMapping("/findById")
    @ResponseBody
    public Object findById(Integer id) {
        Customer customer = service.findById(id);
        return JsonData.buildSuccess(customer);
    }
}
